﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Revis.VClinicNet.UI.Internal.Mvc.Extensions;

namespace Revis.VClinicNet.UI.Internal.Mvc.Infrastructure
{
    public class ControllerBase : Controller
    {
        private string _controllerName;

        protected long UserId { get; set; }
        protected ClinicUser ClinicUser { get; set; }
        protected static readonly long DefaulUserId = 1;

        protected static readonly string UserMenuXmlFilePath = "~/UserMenu.xml";

        protected ControllerBase()
        {
            UserId = DefaulUserId;
            ClinicUser = null;
        }

        protected ControllerBase(string controllerName)
            : this()
        {
            _controllerName = controllerName;
        }

        protected ControllerBase(long userId)
        {
            UserId = userId;
        }

        protected override void Initialize(RequestContext requestContext)
        {
            ClinicUser user = requestContext.HttpContext.Session.GetInstance<ClinicUser>();
            if (user != null) {
                ClinicUser = user;
                UserId = user.Id;

                string mappedMenuPath = requestContext.HttpContext.Server.MapPath(UserMenuXmlFilePath);
                IEnumerable<IMenuItem> userMenu = XmlMenu.LoadFrom(mappedMenuPath).For(user.Role);
                ViewData.AddInstance<UserMenuViewModel>(new UserMenuViewModel(userMenu));

                ViewData.AddInstance<ClinicUserViewModel>(new ClinicUserViewModel(user));
            }
            base.Initialize(requestContext);
        }

        protected void StoreUser(ClinicUser user)
        {
            Session.AddInstance<ClinicUser>(user);
        }

        protected void ForgetUser()
        {
            Session.RemoveInstance<ClinicUser>();
        }

        protected string BackLinkUrl()
        {
            IBackLink backLink = Session.GetInstance<IBackLink>();
            string url = backLink != null ? backLink.Url : null;
            return url ?? Controllers.LoginController.HomePageUrl[ClinicUser.Role];
        }

        protected ViewResult ErrorView(string msg, string actionName)
        {
            return View("Error", new HandleErrorInfo(new Exception(msg), _controllerName, actionName));
        }
    }
}
